//
//  LoginViewController.swift
//  MyKebiao
//
//  Created by David on 2016/12/2.
//  Copyright © 2016年 David. All rights reserved.
//

import UIKit

let serverURL = "http://119.29.225.180"



class UDLoginViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    
    var kebiaoGrid: NSMutableArray?
    
    fileprivate var tableView:UITableView!
    var navigationBar:UINavigationBar!
    
    fileprivate var emailTextField:UDTextField!
    fileprivate var passwordTextField:UDTextField!
    fileprivate var verifyTextField:UDTextField!
    //private var forgetPswBtn:UIButton!
    fileprivate var verifyImg:UIButton!
    fileprivate var loginBtn:UIButton!
    fileprivate var msg:UILabel!
    
    fileprivate var spinnerBG:UIView!
    fileprivate var verifyNeed = false
    fileprivate var requireVerify:Bool{
        get{
            return verifyNeed
        }
        set(val){
            verifyNeed = val
            
            if val{
                self.passwordTextField.returnKeyType = .next
                self.verifyTextField.alpha = 1
                //self.forgetPswBtn.frame.origin.y = self.verifyImg.frame.origin.y
                self.verifyImg.alpha = 1
                refreshVerifyImg()
                
            }
        }
    }
    @objc fileprivate func refreshVerifyImg(){
        
        URLSession.shared.dataTask(with: URL(string: "\(serverURL)")!, completionHandler: {(data:Data?, resp:URLResponse?, err:Error?) in
            if err == nil{
                if data != nil{
                    DispatchQueue.main.async(execute: {
                        self.verifyImg.setImage(UIImage(data: data!), for: .normal)
                    })
                }
            }
        }).resume()
        
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 使用check&jump
        //        if NSUserDefaults.standardUserDefaults().objectForKey("user") != nil{
        // 跳转至其他页面
        //            presentViewController(mainViewController, animated: false, completion: {
        //
        //            })
        //            return
        //        }
        //view.backgroundColor = UIColor.whiteColor()
        
        
        
        tableView = UITableView(frame: CGRect(x: 0, y: 64, width: view.bounds.width, height: view.bounds.height - 64), style: .grouped)
        tableView.keyboardDismissMode = .onDrag
        tableView.allowsSelection = false
        self.view.addSubview(tableView)
        
        msg = UILabel(frame: CGRect(x: 0, y: 40, width: self.view.frame.width, height: 24))
        msg.textAlignment = .center
        msg.font = UIFont.systemFont(ofSize: 12)
        
        msg.textColor = UIColor.brown
        msg.backgroundColor = UIColor.orange
        msg.alpha = 0
        msg.center.y = 52
        view.addSubview(msg)
        
        navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 64))
        view.addSubview(navigationBar)
//        navigationBar.barStyle = .black
//        navigationBar.tintColor = UIColor.white
//        navigationBar.barTintColor = UIColor.white
        
        let navItem = UINavigationItem(title: "登陆")
        navigationBar.pushItem(navItem, animated: true)
        // MARK:注册按钮
//        navItem.rightBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(UDLoginViewController.gotoReg))
        navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(UDLoginViewController.dismissVC))
        
        emailTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.frame.width - 32, height: 32))
        emailTextField.boderWidth = 0
        emailTextField.addTarget(self, action: #selector(UDLoginViewController.nextInput(_:)), for: .editingDidEndOnExit)
        
        passwordTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.frame.width - 32, height: 32))
        passwordTextField.boderWidth = 0
        passwordTextField.textFieldType = .password
        passwordTextField.addTarget(self, action: #selector(UDLoginViewController.nextInput(_:)), for: .editingDidEndOnExit)
        
        verifyTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.bounds.width - 8 - 83.2 - 32, height: 32))
        verifyTextField.boderWidth = 0
        verifyTextField.textFieldType = .verify
        verifyTextField.addTarget(self, action: #selector(UDLoginViewController.nextInput(_:)), for: .editingDidEndOnExit)
        
        // MARK:DEL: forget password
        /*
         forgetPswBtn = UIButton(type: .System)
         forgetPswBtn.frame = CGRect(x: 8, y: 24 + emailTextField.frame.height + 8 + passwordTextField.frame.height + 8 + verifyTextField.frame.height + 8, width: 75, height: 32)
         forgetPswBtn.setTitle("忘记密码", forState: .Normal)
         forgetPswBtn.titleLabel?.textAlignment = .Left
         //        self.scrollView.addSubview(self.forgetPswBtn)
         */
        
        verifyImg = UIButton(frame: CGRect(x: self.view.bounds.width - 83.2 - 16, y: 8, width: 83.2, height: 32))
        verifyImg.backgroundColor = UIColor.gray
        verifyImg.contentMode = .scaleToFill
        verifyImg.addTarget(self, action: #selector(UDLoginViewController.refreshVerifyImg), for: .touchUpInside)
        
        
        
        loginBtn = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 48))
        loginBtn.setTitle("登陆", for: UIControlState())
        loginBtn.backgroundColor = UIColor.green
        loginBtn.setTitleColor(UIColor.white, for: UIControlState())
        loginBtn.addTarget(self, action: #selector(UDLoginViewController.login), for: .touchUpInside)
        loginBtn.adjustsImageWhenDisabled = true
        
        //checkNeedVerify()
        
        spinnerBG = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinnerBG.center = view.center
        spinnerBG.backgroundColor = UIColor(white: 0, alpha: 0.75)
        spinnerBG.layer.cornerRadius = 5
        view.addSubview(spinnerBG)
        let spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinner.center = CGPoint(x: 25, y: 25)
        spinner.activityIndicatorViewStyle = .white
        spinner.startAnimating()
        spinnerBG.addSubview(spinner)
        
        
        self.spinnerBG.alpha = 0
        
        requireVerify = true
        
        tableView.delegate = self
        tableView.dataSource = self
        
        
        if UserDefaults.standard.object(forKey: "uname") != nil{
            emailTextField.text = UserDefaults.standard.object(forKey: "uname") as? String
        }
        if UserDefaults.standard.object(forKey: "psw") != nil{
            passwordTextField.text = UserDefaults.standard.object(forKey: "psw") as? String
        }
        
        self.emailTextField.becomeFirstResponder()
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return 3
        }
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 48
    }
    /*
     func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
     if section == 0{
     return 32
     }
     if section == 1{
     return 1
     }
     return 0
     }
     func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
     if section == 0{
     return msg
     }
     return nil
     }
     */
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "row")
        if indexPath.section == 0{
            switch indexPath.row {
            case 0:
                cell.addSubview(emailTextField)
                break
            case 1:
                cell.addSubview(passwordTextField)
                break
            case 2:
                cell.addSubview(verifyTextField)
                cell.addSubview(verifyImg)
                break
            default:
                break
            }
        }else if indexPath.section == 1 && indexPath.row == 0 {
            cell.addSubview(loginBtn)
        }
        return cell
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @objc fileprivate func nextInput(_ sender: UDTextField){
        // 实现点击next可以切换输入框以及登陆
        switch sender.tabIndex {
        case 0:
            passwordTextField.becomeFirstResponder()
            break
        case 1:
            if requireVerify{
                verifyTextField.becomeFirstResponder()
            }else{
                login()
            }
            break
        case 2:
            login()
            break
        default:
            break
        }
    }
    
    @objc fileprivate func login(){
        if checkInput() {
            postRequest()
        }
    }
    
    fileprivate func checkInput() ->Bool{
        
        // 检查输入是否合法，不合法的不提交服务器，减少请求
        if emailTextField.text == ""{
            setErrorMsg("请输入用户名")
            emailTextField.becomeFirstResponder()
            return false
        }
        // MARK: 打开这段代码检查邮箱地址
        /*
         if emailTextField.text!.componentsSeparatedByString("@").count != 2{
         setErrorMsg("邮箱地址不正确")
         emailTextField.becomeFirstResponder()
         return false
         }
         */
        
        if passwordTextField.text == ""{
            setErrorMsg("请输入密码")
            passwordTextField.becomeFirstResponder()
            return false
        }
        
        // MARK: 打开这段代码检查密码长度
        /*
         if passwordTextField.text?.characters.count < 6{
         setErrorMsg("密码长度不足")
         passwordTextField.becomeFirstResponder()
         return false
         }
         */
        
        if requireVerify{
            if verifyTextField.text == ""{
                setErrorMsg("请输入验证码")
                verifyTextField.becomeFirstResponder()
                return false
            }
        }
        setErrorMsg("")
        return true
    }
    
    fileprivate func postingStatus(_ status: Bool){
        // 切换通讯状态，与服务器通讯中禁用所有按钮防止多次提交
        emailTextField.isEnabled = !status
        passwordTextField.isEnabled = !status
        verifyTextField.isEnabled = !status
        verifyImg.isEnabled = !status
        loginBtn.isEnabled = !status
        if status{
            spinnerBG.alpha = 1
        }else{
            spinnerBG.alpha = 0
        }
    }
    
    fileprivate func postRequest(){
        // 提交数据
        postingStatus(true)
        
        var resq = URLRequest(url: URL(string: "\(serverURL)")!)
        resq.httpMethod = "POST"
        resq.httpBody = "uname=\(emailTextField.text!)&psw=\(passwordTextField.text!)&verify=\(verifyTextField.text!)".data(using: String.Encoding.utf8)
        
        URLSession.shared.dataTask(with: resq, completionHandler: {(returnData:Data?, resp:URLResponse?, err:Error?) in
            var connected = false
            if err == nil{
                if let data = returnData{
                    print(String(data: data, encoding: String.Encoding.utf8)!)
                    connected = true
//                    DispatchQueue.main.async(execute: {
//                        self.handleResult(data)
//                    })
                    let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
                    var dataLegit = false
                    if jsonObj != nil{
                        let jsonDic = jsonObj as? NSDictionary
                        if jsonDic != nil{
                            let status = jsonDic?.object(forKey: "status") as? String
                            if status == "yes" {
                                dataLegit = true
                                UserDefaults.standard.set(self.emailTextField.text!, forKey: "uname")
                                DispatchQueue.main.async {
                                    self.dismiss(animated: true, completion: nil)
                                }
                            }
                            
                                
                                
                        }
                        
                    }
                    
                    if !dataLegit {
                        DispatchQueue.main.async(execute: {
                            self.setErrorMsg("发生数据错误")
                            self.postingStatus(false)
                        })
                    }
                }
            }
            if !connected{
                DispatchQueue.main.async(execute: {
                    self.setErrorMsg("网络错误")
                    self.postingStatus(false)
                })
            }
        }).resume()
        
        
    }
    
    
    fileprivate func setErrorMsg(_ message: String){
        // 显示错误信息，做一个摇头的动画
        
        msg.text = message
        if message != ""{
            self.msg.alpha = 1
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveLinear, animations: {
                
                self.msg.center.y = 76
            }, completion: { (finished) in
                UIView.animate(withDuration: 0.3, delay: 3, options: .curveLinear, animations: {
                    self.msg.center.y = 52
                }, completion: { (finished1) in
                    self.msg.alpha = 0
                })
            })
        }
    }
    
    
    func dismissVC(){
        // 关闭页面
        self.dismiss(animated: true, completion: nil)
    }
    
    
    func doubleDismissRegView() {
        self.dismiss(animated: true, completion: nil)
    }
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    func isColorConfilc(_ id: Int, color: Int) -> Bool?{
        if kebiaoGrid != nil{
            let rightItem = kebiaoGrid!.object(at: id)
            let rightDic = rightItem  as? NSDictionary
            if rightDic != nil{
                let thatColor = rightDic?.object(forKey: "color") as! Int
                if color == thatColor{
                    return true
                }
            }else{
                let rightAry = rightItem as? NSArray
                if rightAry != nil{
                    let rightFirstDic = rightAry?.firstObject as? NSDictionary
                    if rightFirstDic != nil{
                        let thatColor = rightFirstDic?.object(forKey: "color") as! Int
                        if color == thatColor{
                            return true
                        }
                    }
                }
            }
            return false
        }
        
        return nil
    }
}


